package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;

    @Autowired
    private IFollowService followService;

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        //查询blog有关的用户信息
        User user = userMapper.selectById(blog.getUserId());
        if (user == null) {
            return Result.fail("该用户已注销");
        }

        //统计浏览量
        stringRedisTemplate.opsForHyperLogLog().add(RedisConstants.UV_BLOG + blog.getId(), user.getId().toString());
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + id, UserHolder.getUser().getId().toString());
        //整合信息
        blog.setIsLike(score != null);
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
        return Result.ok(blog);
    }

    @Override
    public Result likeBlog(Long id) {
        //获取用户id
        UserDTO user = UserHolder.getUser();
        if (user == null) return Result.fail("请先登录");
        Long userId = user.getId();
        //判断用户是否点过赞
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
        if (score != null) {
            //点过赞，移除redis中的用户信息，并且数据库点赞数-1
            boolean isSuccess = update().eq("id", id).setSql("liked = liked - 1").update();
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
            }
        } else {
            //没点过赞，将用户id加入redis，数据库点赞数+1;
            boolean isSuccess = update().eq("id", id).setSql("liked = liked + 1").update();
            if (isSuccess) {
                Long count = stringRedisTemplate.opsForZSet().count(RedisConstants.BLOG_LIKED_KEY + id, -1.0, 1.1);
                stringRedisTemplate.opsForZSet().add(RedisConstants.BLOG_LIKED_KEY + id, userId.toString(), System.currentTimeMillis());
            }
        }
        //返回数据
        return Result.ok();
    }

    @Override
    public Result likedUserTop5(Long id) {
        Set<String> rangeSet = stringRedisTemplate.opsForZSet().range(RedisConstants.BLOG_LIKED_KEY + id, 0, 4);
        if (rangeSet == null || rangeSet.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> userIdList = rangeSet.stream().map(Long::valueOf).collect(Collectors.toList());
        String strIds = StrUtil.join(",", userIdList);

        List<UserDTO> userDTOList = userService.query()
                .in("id", userIdList)
                .last("ORDER BY FIELD(id," + strIds + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOList);
    }

    @Override
    public Result blogOfUser(Long id, Long current) {
        Page<Blog> blogPage = query().eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        if (blogPage == null) {
            return Result.ok();
        }
        List<Blog> records = blogPage.getRecords();
        return Result.ok(records);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            return Result.fail("新增探店笔记失败");
        }
        //查询笔记作者所有粉丝
        List<Follow> list = followService.query().eq("follow_user_id", user.getId()).list();

        //推送笔记id给粉丝
        for (Follow follow : list) {
            //获取粉丝id
            Long userId = follow.getUserId();
            //推送到该粉丝的收件箱
            stringRedisTemplate.opsForZSet().add(RedisConstants.FEED_KEY + userId, blog.getId().toString(), System.currentTimeMillis());

        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        //查询收件箱
        String key = RedisConstants.FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        //解析数据: blogId, score(时间戳), offset
        long minTime = 0;
        int os = 1;
        List<Long> ids = new ArrayList<>(typedTuples.size());
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            ids.add(Long.valueOf(typedTuple.getValue()));
            long time = typedTuple.getScore().longValue();
            if (time == minTime) {
                os++;
            } else {
                os = 1;
                minTime = time;
            }
        }
        String idsStr = StrUtil.join(",", ids);
        //根据id查询blog
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idsStr + ")").list();
        for (Blog blog : blogs) {
            //判断用户是否点过赞
            Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + blog.getId(), userId.toString());
            blog.setIsLike(score != null);
            User user = userService.getById(blog.getUserId());
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
        }
        //封装并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(os);
        return Result.ok(scrollResult);
    }

    @Override
    public Result blogUv(Long blogId) {
        Long size = stringRedisTemplate.opsForHyperLogLog().size(RedisConstants.UV_BLOG + blogId);
        return Result.ok(size);
    }
}
